import React, { useState, useEffect } from 'react';
import { 
  Card, 
  Form, 
  Input, 
  Button, 
  Space, 
  message, 
  Tabs, 
  Switch, 
  Select, 
  InputNumber,
  Upload,
  Row,
  Col,
  Divider,
  Alert,
  TimePicker,
  Slider
} from 'antd';
import { 
  SaveOutlined, 
  ReloadOutlined, 
  UploadOutlined,
  SettingOutlined,
  SecurityScanOutlined,
  DatabaseOutlined,
  NotificationOutlined,
  GlobalOutlined
} from '@ant-design/icons';
import type { UploadProps } from 'antd';
import dayjs from 'dayjs';

const { TextArea } = Input;
const { Option } = Select;
const { TabPane } = Tabs;

// 系统设置数据接口
interface SystemSettings {
  // 基本设置
  systemName: string;
  systemVersion: string;
  systemDescription: string;
  companyName: string;
  companyLogo?: string;
  contactEmail: string;
  contactPhone: string;
  
  // 安全设置
  passwordMinLength: number;
  passwordComplexity: boolean;
  sessionTimeout: number;
  maxLoginAttempts: number;
  enableTwoFactor: boolean;
  
  // 数据库设置
  backupEnabled: boolean;
  backupInterval: number;
  backupRetentionDays: number;
  backupTime: string;
  
  // 通知设置
  emailNotification: boolean;
  smsNotification: boolean;
  systemAlerts: boolean;
  maintenanceNotice: boolean;
  
  // 界面设置
  theme: 'light' | 'dark';
  language: string;
  timezone: string;
  dateFormat: string;
  pageSize: number;
}

// 默认设置
const defaultSettings: SystemSettings = {
  systemName: '智能楼宇管理系统',
  systemVersion: '1.0.0',
  systemDescription: '基于React的智能楼宇综合管理平台',
  companyName: '华发集团',
  contactEmail: 'admin@huafa.com',
  contactPhone: '400-888-8888',
  
  passwordMinLength: 8,
  passwordComplexity: true,
  sessionTimeout: 30,
  maxLoginAttempts: 5,
  enableTwoFactor: false,
  
  backupEnabled: true,
  backupInterval: 24,
  backupRetentionDays: 30,
  backupTime: '02:00',
  
  emailNotification: true,
  smsNotification: false,
  systemAlerts: true,
  maintenanceNotice: true,
  
  theme: 'light',
  language: 'zh-CN',
  timezone: 'Asia/Shanghai',
  dateFormat: 'YYYY-MM-DD',
  pageSize: 20
};

const SystemSettings: React.FC = () => {
  const [settings, setSettings] = useState<SystemSettings>(defaultSettings);
  const [loading, setLoading] = useState(false);
  const [activeTab, setActiveTab] = useState('basic');
  
  // 仅为当前活动 Tab（初始为基本设置）保留实例，其他使用 Form 内部实例以避免未绑定警告
  const [basicForm] = Form.useForm();

  // 初始化表单数据
  useEffect(() => {
    basicForm.setFieldsValue({
      systemName: settings.systemName,
      systemVersion: settings.systemVersion,
      systemDescription: settings.systemDescription,
      companyName: settings.companyName,
      contactEmail: settings.contactEmail,
      contactPhone: settings.contactPhone,
    });

    // 其他 Tab 的表单使用 initialValues 渲染，避免在未挂载时创建未绑定的实例
  }, [settings]);

  // 文件上传配置
  const uploadProps: UploadProps = {
    name: 'file',
    action: '/api/upload',
    headers: {
      authorization: 'authorization-text',
    },
    onChange(info) {
      if (info.file.status === 'done') {
        message.success(`${info.file.name} 文件上传成功`);
      } else if (info.file.status === 'error') {
        message.error(`${info.file.name} 文件上传失败`);
      }
    },
  };

  // 保存基本设置
  const handleBasicSave = (values: any) => {
    setLoading(true);
    setTimeout(() => {
      setSettings(prev => ({ ...prev, ...values }));
      setLoading(false);
      message.success('基本设置保存成功');
    }, 1000);
  };

  // 保存安全设置
  const handleSecuritySave = (values: any) => {
    setLoading(true);
    setTimeout(() => {
      setSettings(prev => ({ ...prev, ...values }));
      setLoading(false);
      message.success('安全设置保存成功');
    }, 1000);
  };

  // 保存数据库设置
  const handleDatabaseSave = (values: any) => {
    setLoading(true);
    const formattedValues = {
      ...values,
      backupTime: values.backupTime.format('HH:mm')
    };
    setTimeout(() => {
      setSettings(prev => ({ ...prev, ...formattedValues }));
      setLoading(false);
      message.success('数据库设置保存成功');
    }, 1000);
  };

  // 保存通知设置
  const handleNotificationSave = (values: any) => {
    setLoading(true);
    setTimeout(() => {
      setSettings(prev => ({ ...prev, ...values }));
      setLoading(false);
      message.success('通知设置保存成功');
    }, 1000);
  };

  // 保存界面设置
  const handleInterfaceSave = (values: any) => {
    setLoading(true);
    setTimeout(() => {
      setSettings(prev => ({ ...prev, ...values }));
      setLoading(false);
      message.success('界面设置保存成功');
    }, 1000);
  };

  // 重置设置
  const handleReset = () => {
    setSettings(defaultSettings);
    message.success('设置已重置为默认值');
  };

  // 立即备份
  const handleBackupNow = () => {
    setLoading(true);
    setTimeout(() => {
      setLoading(false);
      message.success('数据备份完成');
    }, 2000);
  };

  // 测试邮件通知
  const handleTestEmail = () => {
    setLoading(true);
    setTimeout(() => {
      setLoading(false);
      message.success('测试邮件发送成功');
    }, 1000);
  };

  return (
    <div style={{ padding: '24px' }}>
      <Card>
        <Tabs activeKey={activeTab} onChange={setActiveTab}>
          {/* 基本设置 */}
          <TabPane 
            tab={
              <span>
                <SettingOutlined />
                基本设置
              </span>
            } 
            key="basic"
          >
            <Form
              form={basicForm}
              layout="vertical"
              onFinish={handleBasicSave}
            >
              <Row gutter={24}>
                <Col span={12}>
                  <Form.Item
                    name="systemName"
                    label="系统名称"
                    rules={[{ required: true, message: '请输入系统名称' }]}
                  >
                    <Input placeholder="请输入系统名称" />
                  </Form.Item>
                </Col>
                <Col span={12}>
                  <Form.Item
                    name="systemVersion"
                    label="系统版本"
                    rules={[{ required: true, message: '请输入系统版本' }]}
                  >
                    <Input placeholder="请输入系统版本" />
                  </Form.Item>
                </Col>
              </Row>
              
              <Form.Item
                name="systemDescription"
                label="系统描述"
              >
                <TextArea rows={3} placeholder="请输入系统描述" />
              </Form.Item>

              <Row gutter={24}>
                <Col span={12}>
                  <Form.Item
                    name="companyName"
                    label="公司名称"
                    rules={[{ required: true, message: '请输入公司名称' }]}
                  >
                    <Input placeholder="请输入公司名称" />
                  </Form.Item>
                </Col>
                <Col span={12}>
                  <Form.Item
                    name="companyLogo"
                    label="公司Logo"
                  >
                    <Upload {...uploadProps}>
                      <Button icon={<UploadOutlined />}>点击上传</Button>
                    </Upload>
                  </Form.Item>
                </Col>
              </Row>

              <Row gutter={24}>
                <Col span={12}>
                  <Form.Item
                    name="contactEmail"
                    label="联系邮箱"
                    rules={[
                      { required: true, message: '请输入联系邮箱' },
                      { type: 'email', message: '请输入正确的邮箱格式' }
                    ]}
                  >
                    <Input placeholder="请输入联系邮箱" />
                  </Form.Item>
                </Col>
                <Col span={12}>
                  <Form.Item
                    name="contactPhone"
                    label="联系电话"
                    rules={[{ required: true, message: '请输入联系电话' }]}
                  >
                    <Input placeholder="请输入联系电话" />
                  </Form.Item>
                </Col>
              </Row>

              <Form.Item style={{ textAlign: 'right' }}>
                <Space>
                  <Button onClick={handleReset}>
                    重置
                  </Button>
                  <Button type="primary" htmlType="submit" loading={loading}>
                    <SaveOutlined />
                    保存设置
                  </Button>
                </Space>
              </Form.Item>
            </Form>
          </TabPane>

          {/* 安全设置 */}
          <TabPane 
            tab={
              <span>
                <SecurityScanOutlined />
                安全设置
              </span>
            } 
            key="security"
          >
            <Alert
              message="安全提示"
              description="修改安全设置可能会影响用户登录，请谨慎操作。"
              type="warning"
              showIcon
              style={{ marginBottom: 24 }}
            />
            
            <Form
              layout="vertical"
              onFinish={handleSecuritySave}
              initialValues={{
                passwordMinLength: settings.passwordMinLength,
                passwordComplexity: settings.passwordComplexity,
                sessionTimeout: settings.sessionTimeout,
                maxLoginAttempts: settings.maxLoginAttempts,
                enableTwoFactor: settings.enableTwoFactor,
              }}
            >
              <Row gutter={24}>
                <Col span={12}>
                  <Form.Item
                    name="passwordMinLength"
                    label="密码最小长度"
                    rules={[{ required: true, message: '请设置密码最小长度' }]}
                  >
                    <InputNumber min={6} max={20} style={{ width: '100%' }} />
                  </Form.Item>
                </Col>
                <Col span={12}>
                  <Form.Item
                    name="passwordComplexity"
                    label="启用密码复杂度检查"
                    valuePropName="checked"
                  >
                    <Switch checkedChildren="启用" unCheckedChildren="禁用" />
                  </Form.Item>
                </Col>
              </Row>

              <Row gutter={24}>
                <Col span={12}>
                  <Form.Item
                    name="sessionTimeout"
                    label="会话超时时间（分钟）"
                    rules={[{ required: true, message: '请设置会话超时时间' }]}
                  >
                    <InputNumber min={5} max={480} style={{ width: '100%' }} />
                  </Form.Item>
                </Col>
                <Col span={12}>
                  <Form.Item
                    name="maxLoginAttempts"
                    label="最大登录尝试次数"
                    rules={[{ required: true, message: '请设置最大登录尝试次数' }]}
                  >
                    <InputNumber min={3} max={10} style={{ width: '100%' }} />
                  </Form.Item>
                </Col>
              </Row>

              <Form.Item
                name="enableTwoFactor"
                label="启用双因子认证"
                valuePropName="checked"
              >
                <Switch checkedChildren="启用" unCheckedChildren="禁用" />
              </Form.Item>

              <Form.Item style={{ textAlign: 'right' }}>
                <Button type="primary" htmlType="submit" loading={loading}>
                  <SaveOutlined />
                  保存设置
                </Button>
              </Form.Item>
            </Form>
          </TabPane>

          {/* 数据库设置 */}
          <TabPane 
            tab={
              <span>
                <DatabaseOutlined />
                数据库设置
              </span>
            } 
            key="database"
          >
            <Form
              layout="vertical"
              onFinish={handleDatabaseSave}
              initialValues={{
                backupEnabled: settings.backupEnabled,
                backupInterval: settings.backupInterval,
                backupRetentionDays: settings.backupRetentionDays,
                backupTime: dayjs(settings.backupTime, 'HH:mm'),
              }}
            >
              <Form.Item
                name="backupEnabled"
                label="启用自动备份"
                valuePropName="checked"
              >
                <Switch checkedChildren="启用" unCheckedChildren="禁用" />
              </Form.Item>

              <Row gutter={24}>
                <Col span={8}>
                  <Form.Item
                    name="backupInterval"
                    label="备份间隔（小时）"
                    rules={[{ required: true, message: '请设置备份间隔' }]}
                  >
                    <InputNumber min={1} max={168} style={{ width: '100%' }} />
                  </Form.Item>
                </Col>
                <Col span={8}>
                  <Form.Item
                    name="backupRetentionDays"
                    label="备份保留天数"
                    rules={[{ required: true, message: '请设置备份保留天数' }]}
                  >
                    <InputNumber min={1} max={365} style={{ width: '100%' }} />
                  </Form.Item>
                </Col>
                <Col span={8}>
                  <Form.Item
                    name="backupTime"
                    label="备份时间"
                    rules={[{ required: true, message: '请设置备份时间' }]}
                  >
                    <TimePicker format="HH:mm" style={{ width: '100%' }} />
                  </Form.Item>
                </Col>
              </Row>

              <Divider />

              <Form.Item style={{ textAlign: 'right' }}>
                <Space>
                  <Button onClick={handleBackupNow} loading={loading}>
                    立即备份
                  </Button>
                  <Button type="primary" htmlType="submit" loading={loading}>
                    <SaveOutlined />
                    保存设置
                  </Button>
                </Space>
              </Form.Item>
            </Form>
          </TabPane>

          {/* 通知设置 */}
          <TabPane 
            tab={
              <span>
                <NotificationOutlined />
                通知设置
              </span>
            } 
            key="notification"
          >
            <Form
              layout="vertical"
              onFinish={handleNotificationSave}
              initialValues={{
                emailNotification: settings.emailNotification,
                smsNotification: settings.smsNotification,
                systemAlerts: settings.systemAlerts,
                maintenanceNotice: settings.maintenanceNotice,
              }}
            >
              <Row gutter={24}>
                <Col span={12}>
                  <Form.Item
                    name="emailNotification"
                    label="邮件通知"
                    valuePropName="checked"
                  >
                    <Switch checkedChildren="启用" unCheckedChildren="禁用" />
                  </Form.Item>
                </Col>
                <Col span={12}>
                  <Form.Item
                    name="smsNotification"
                    label="短信通知"
                    valuePropName="checked"
                  >
                    <Switch checkedChildren="启用" unCheckedChildren="禁用" />
                  </Form.Item>
                </Col>
              </Row>

              <Row gutter={24}>
                <Col span={12}>
                  <Form.Item
                    name="systemAlerts"
                    label="系统告警"
                    valuePropName="checked"
                  >
                    <Switch checkedChildren="启用" unCheckedChildren="禁用" />
                  </Form.Item>
                </Col>
                <Col span={12}>
                  <Form.Item
                    name="maintenanceNotice"
                    label="维护通知"
                    valuePropName="checked"
                  >
                    <Switch checkedChildren="启用" unCheckedChildren="禁用" />
                  </Form.Item>
                </Col>
              </Row>

              <Divider />

              <Form.Item style={{ textAlign: 'right' }}>
                <Space>
                  <Button onClick={handleTestEmail} loading={loading}>
                    测试邮件
                  </Button>
                  <Button type="primary" htmlType="submit" loading={loading}>
                    <SaveOutlined />
                    保存设置
                  </Button>
                </Space>
              </Form.Item>
            </Form>
          </TabPane>

          {/* 界面设置 */}
          <TabPane 
            tab={
              <span>
                <GlobalOutlined />
                界面设置
              </span>
            } 
            key="interface"
          >
            <Form
              layout="vertical"
              onFinish={handleInterfaceSave}
              initialValues={{
                theme: settings.theme,
                language: settings.language,
                timezone: settings.timezone,
                dateFormat: settings.dateFormat,
                pageSize: settings.pageSize,
              }}
            >
              <Row gutter={24}>
                <Col span={12}>
                  <Form.Item
                    name="theme"
                    label="主题模式"
                    rules={[{ required: true, message: '请选择主题模式' }]}
                  >
                    <Select>
                      <Option value="light">浅色主题</Option>
                      <Option value="dark">深色主题</Option>
                    </Select>
                  </Form.Item>
                </Col>
                <Col span={12}>
                  <Form.Item
                    name="language"
                    label="系统语言"
                    rules={[{ required: true, message: '请选择系统语言' }]}
                  >
                    <Select>
                      <Option value="zh-CN">简体中文</Option>
                      <Option value="en-US">English</Option>
                      <Option value="zh-TW">繁體中文</Option>
                    </Select>
                  </Form.Item>
                </Col>
              </Row>

              <Row gutter={24}>
                <Col span={12}>
                  <Form.Item
                    name="timezone"
                    label="时区设置"
                    rules={[{ required: true, message: '请选择时区' }]}
                  >
                    <Select>
                      <Option value="Asia/Shanghai">北京时间 (UTC+8)</Option>
                      <Option value="Asia/Tokyo">东京时间 (UTC+9)</Option>
                      <Option value="America/New_York">纽约时间 (UTC-5)</Option>
                      <Option value="Europe/London">伦敦时间 (UTC+0)</Option>
                    </Select>
                  </Form.Item>
                </Col>
                <Col span={12}>
                  <Form.Item
                    name="dateFormat"
                    label="日期格式"
                    rules={[{ required: true, message: '请选择日期格式' }]}
                  >
                    <Select>
                      <Option value="YYYY-MM-DD">2024-01-20</Option>
                      <Option value="DD/MM/YYYY">20/01/2024</Option>
                      <Option value="MM/DD/YYYY">01/20/2024</Option>
                      <Option value="YYYY年MM月DD日">2024年01月20日</Option>
                    </Select>
                  </Form.Item>
                </Col>
              </Row>

              <Form.Item
                name="pageSize"
                label="每页显示条数"
                rules={[{ required: true, message: '请设置每页显示条数' }]}
              >
                <Slider
                  min={10}
                  max={100}
                  step={10}
                  marks={{
                    10: '10',
                    20: '20',
                    50: '50',
                    100: '100'
                  }}
                />
              </Form.Item>

              <Form.Item style={{ textAlign: 'right' }}>
                <Button type="primary" htmlType="submit" loading={loading}>
                  <SaveOutlined />
                  保存设置
                </Button>
              </Form.Item>
            </Form>
          </TabPane>
        </Tabs>
      </Card>
    </div>
  );
};

export default SystemSettings;